package global

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"gorm.io/gorm"
	"hcy-api/lib/db"
	"hcy-api/lib/log"
	"hcy-api/structs/base"
)

var (
	IdpConf = new(base.IdpConf)
	DB      *gorm.DB
)

func InitIdpConfig(configName string) {
	v := viper.New()
	v.SetConfigType("yaml")
	v.SetConfigName(configName)
	v.AddConfigPath(".")
	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Sprintf("加载配置文件失败： %v", err))
	}
	err = v.Unmarshal(IdpConf)
	if err != nil {
		panic(fmt.Sprintf("不合法的配置信息： %v", err))
	}
	log.InitLog(IdpConf.Log.Name, IdpConf.Log.Lv)
	InitDB()
}

func InitDB() {
	var err error
	DB, err = db.GetDB(IdpConf.DB.Supper, IdpConf.DB.ShowSqlLog, IdpConf.DB.Source, "")
	if err != nil {
		logrus.Panicf("连接数据库失败：%v", err)
	}
	autoMigrate()
}
